// 初始化页面
document.addEventListener('DOMContentLoaded', function() {
    // 初始化导航栏
    initNavbar();

    // 初始化表单验证
    initFormValidation();

    // 初始化文件上传
    initFileUpload();

    // 初始化表格
    initTables();
});

// 初始化导航栏
function initNavbar() {
    // 导航栏滚动效果
    window.addEventListener('scroll', function() {
        const navbar = document.getElementById('main-navbar');
        if (window.scrollY > 50) {
            navbar.classList.add('bg-white', 'shadow-md');
            navbar.classList.remove('bg-transparent');
        } else {
            navbar.classList.remove('bg-white', 'shadow-md');
            navbar.classList.add('bg-transparent');
        }
    });

    // 移动端菜单切换
    const menuToggle = document.getElementById('menu-toggle');
    const mobileMenu = document.getElementById('mobile-menu');

    if (menuToggle && mobileMenu) {
        menuToggle.addEventListener('click', function() {
            mobileMenu.classList.toggle('hidden');
        });
    }
}

// 初始化表单验证
function initFormValidation() {
    const forms = document.querySelectorAll('form.needs-validation');

    forms.forEach(form => {
        form.addEventListener('submit', function(event) {
            if (!form.checkValidity()) {
                event.preventDefault();
                event.stopPropagation();
            }
            form.classList.add('was-validated');
        });
    });
}

// 初始化文件上传
function initFileUpload() {
    const fileInputs = document.querySelectorAll('.custom-file-input');

    fileInputs.forEach(input => {
        input.addEventListener('change', function() {
            const fileName = this.value.split('\\').pop();
            const label = this.nextElementSibling;
            label.textContent = fileName;
        });
    });
}

// 初始化表格
function initTables() {
    const tables = document.querySelectorAll('.data-table');

    tables.forEach(table => {
        // 表格排序功能
        const headers = table.querySelectorAll('th[data-sort]');

        headers.forEach(header => {
            header.addEventListener('click', function() {
                const sortField = this.getAttribute('data-sort');
                const sortDirection = this.getAttribute('data-direction') === 'asc' ? 'desc' : 'asc';

                // 更新排序图标
                headers.forEach(h => {
                    h.setAttribute('data-direction', '');
                    h.querySelector('.sort-icon').innerHTML = '';
                });

                this.setAttribute('data-direction', sortDirection);
                this.querySelector('.sort-icon').innerHTML = sortDirection === 'asc' ? '↑' : '↓';

                // 实际排序逻辑应由后端处理，这里只更新UI
                fetchTableData(sortField, sortDirection);
            });
        });
    });
}

// 获取表格数据（示例）
function fetchTableData(sortField, sortDirection) {
    // 这里应使用AJAX从后端获取数据
    console.log(`Fetching data sorted by ${sortField} ${sortDirection}`);

    // 模拟加载状态
    const loadingIndicator = document.getElementById('table-loading');
    if (loadingIndicator) {
        loadingIndicator.classList.remove('hidden');
    }

    // 模拟数据加载延迟
    setTimeout(() => {
        if (loadingIndicator) {
            loadingIndicator.classList.add('hidden');
        }
    }, 800);
}

// 专利年费提醒功能
function checkAnnualFeeReminders() {
    fetch('/api/patents/annual-fee-reminders')
        .then(response => response.json())
        .then(data => {
            if (data.length > 0) {
                const reminderBadge = document.getElementById('annual-fee-badge');
                const reminderList = document.getElementById('annual-fee-list');

                if (reminderBadge) {
                    reminderBadge.textContent = data.length;
                    reminderBadge.classList.remove('hidden');
                }

                if (reminderList) {
                    let html = '';
                    data.forEach(patent => {
                        html += `
                            <li class="px-4 py-2 border-b">
                                <div class="font-medium">${patent.title}</div>
                                <div class="text-sm text-gray-600">年费到期日: ${formatDate(patent.annualFeeDueDate)}</div>
                            </li>
                        `;
                    });
                    reminderList.innerHTML = html;
                }
            }
        })
        .catch(error => {
            console.error('Error fetching annual fee reminders:', error);
        });
}

// 日期格式化函数
function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
}

// 模态框控制
function openModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.remove('hidden');
        document.body.classList.add('overflow-hidden');
    }
}

function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.add('hidden');
        document.body.classList.remove('overflow-hidden');
    }
}